package com.weita.lightfood.controller;


import com.alibaba.fastjson.JSONObject;
import com.weita.lightfood.model.entity.User;
import com.weita.lightfood.service.UserService;
import com.weita.lightfood.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * @author IT_Monster at 2019/04/08 19:45.
 */
@Api(tags = "登陆接口")
@RestController
public class LoginController {
    @Autowired
    private UserService userService;

    @Value("${wechat.appId}")
    private String appId;
    @Value("${wechat.appSecret}")
    private String appSecret;

    private String openid;
    private String session_key;

    /**
     * 用户登陆
     */
    @ApiOperation("用户登陆")
    @PostMapping("/login")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name",value = "用户名", defaultValue = "admin1"),
            @ApiImplicitParam(name = "password",value = "密码", defaultValue = "123456"),
            @ApiImplicitParam(name = "formId",value = "表单id", defaultValue = "")
    })
    public Result<User> login(String name, String password, String formId) {
        User user;
        try {
            user = userService.login(name, password, formId);
        } catch (Exception e) {
            return Result.fail("登陆错误");
        }
        if (user != null) {
            return Result.success(user);
        } else {
            return Result.fail("登陆失败，请检查用户名和密码");
        }
    }


    @GetMapping("/wechatLogin")
    public Result<User> weixinLogin(String code, int userId){
        //创建httpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response;
        String resultString = "";
        String url = "https://api.weixin.qq.com/sns/jscode2session?" +
                "appid="+appId+"&secret="+appSecret+"&js_code="+code+"&grant_type=authorization_code";
        try {
            URIBuilder uriBuilder = new URIBuilder(url);
            URI uri = uriBuilder.build();
            //构建一个get请求
            HttpGet httpGet = new HttpGet(uri);
            //执行get请求
            response = httpClient.execute(httpGet);
            if ( response.getStatusLine().getStatusCode() == 200 ){
                resultString = EntityUtils.toString(response.getEntity(),"utf-8");
            }
        } catch ( URISyntaxException e ) {
            e.printStackTrace();
        }catch ( IOException e ) {
            e.printStackTrace();
        }
        JSONObject jsonObject = (JSONObject) JSONObject.parse(resultString);
        session_key = jsonObject.get("session_key")+"";
        openid = jsonObject.get("openid")+"";
        System.out.println("openid="+openid);

        try {
            userService.setOrUpdateOpenId(userId, openid);
        } catch ( IOException e ) {
            e.printStackTrace();
        }


        System.out.println("appid="+appId);
        System.out.println("appSecret="+appSecret);
        System.out.println("session_key=="+session_key);
        System.out.println("openid=="+openid);
        return Result.success(resultString);
    }
}
